package com.wanho.qz103.hrsaas.commons.tx.impl;

import com.wanho.qz103.hrsaas.commons.exception.DataAccessException;
import com.wanho.qz103.hrsaas.commons.tx.TxManager;
import com.wanho.qz103.hrsaas.commons.util.JDBCUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;

/**
 * 事务接口实现类
 */
@Slf4j
public class TxManagerImpl implements TxManager {
    @Override
    public void beginTx() throws DataAccessException {
        try {
            // 设置事务手动提交
            JDBCUtil.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("设置事务手动提交异常："+e.getMessage());
            throw new DataAccessException(e.getMessage()) ;
       }
    }

    @Override
    public void commitTx() throws DataAccessException {
        try {
            JDBCUtil.getConnection().commit();
            JDBCUtil.getConnection().setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("提交异常："+e.getMessage());
            throw new DataAccessException(e.getMessage()) ;
        }
    }

    @Override
    public void rollbakTx() throws DataAccessException {
        try {
            JDBCUtil.getConnection().rollback();
            JDBCUtil.getConnection().setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("回滚异常："+e.getMessage());
            throw new DataAccessException(e.getMessage()) ;
        }
    }
}
